package NewChatRoom;

import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;

public class ChatClient extends Thread{

    private boolean running = false;
    private Socket socket;
    private ResultToClient rs = new ResultToClient();
    public ChatClient(Socket socket){
        this.socket = socket;
    }

    public void run(){
        setupClient();
    }

    public Socket getSocket(){
        return socket;
    }

    public void setupClient(){
        try {
            running = true;
            rs.print("连接服务器成功\n");
            //循环监听服务器消息
            InputStream is = socket.getInputStream();
            DataInputStream dis = new DataInputStream(is);
            String msg;
            while (running){
                try {
                    msg = dis.readUTF();
                    rs.print(msg);
                }catch (IOException e){
                    e.printStackTrace();
                    if(running){
                        rs.print("检测到服务器断开连接\n");
                        ClientGUI.b_connect.doClick();
                        break;
                    }

                }
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    public boolean isRunning(){
        return running;
    }

    public void stopChatClient(){
        this.running = false;
        try {
            socket.close();
        }catch (IOException e){
            e.printStackTrace();
        }
    }

}
